package com.scap.authen.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scap.authen.entity.Role;
import com.scap.authen.service.RoleService;
import com.scap.authen.service.SiteService;
import com.scap.authen.util.DataTable;

@Controller
@RequestMapping(value = "/role")
public class RoleController {
	
	@Autowired
	private RoleService voRoleService;	
	@Autowired
	private SiteService voSiteService;
	@Autowired
	private ApplicationContext context;
	DataTable voDataTable = new DataTable();
	
	@RequestMapping( method = RequestMethod.GET)
	public String rolePage ( ModelMap model) {
		model.addAttribute("role",new Role());
		model.addAttribute("page", "Role Management");
		// find all site to drop down list
		List<Object> siteList = voSiteService.findAllSite();
		model.addAttribute("siteList",siteList);
		return "Role/roleManagement";
	} 	
	
	@RequestMapping(value = "/roleDataTables", method = RequestMethod.GET)
	public @ResponseBody String springPaginationDataTables(HttpServletRequest request) throws IOException {	
		//find all site
		List<Object> roleList = voRoleService.findAllRole();
		String searchParameter = request.getParameter("sSearch");
		// search data table
		roleList = voRoleService.getListBasedOnSearchParameter(searchParameter, roleList);	
		return voDataTable.springPaginationDataTables(request,roleList);
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String roleManagement ( @Valid Role role ,BindingResult result,@RequestParam("processType") String vaProcessType, HttpServletRequest request, ModelMap model ) {		
		String vaMessage = "";
		String vaSiteId = request.getParameter("vaSiteId");
		
		// check validate error
		if(result.hasErrors()){
			List<Object> siteList = voSiteService.findAllSite();
			model.addAttribute("siteList",siteList);
			return "Role/roleManagement";
		}		
		
		if (vaProcessType.equals("insertRole")) { 
			// insert case
			vaMessage = voRoleService.saveRole(role, vaSiteId, request);
		}else if (vaProcessType.equals("updateRole")) {
			// update case	
			vaMessage = voRoleService.updateSite( role, vaSiteId,request );	
		}
		List<Object> siteList = voSiteService.findAllSite();
		model.addAttribute("siteList",siteList);
		model.addAttribute("message", vaMessage);
		return  "Role/roleManagement";
	}
}
